import { ref, unref, nextTick } from 'vue'
import { isEmptyVal, isObject } from '@/utils/is'

export function useForm() {
  // Form实例
  const formRef = ref(null)

  // ElForm实例
  const elFormRef = ref(null)

  /**
   * 注册Form和ElForm实例
   * @param ref Form实例
   * @param elRef ElForm实例
   */
  function register(ref, elRef) {
    formRef.value = ref
    elFormRef.value = elRef
  }

  async function getForm() {
    await nextTick()
    const form = unref(formRef)
    if (!form) {
      console.error('The form is not registered. Please use the register method to register')
    }
    return form
  }

  // 内置方法
  const methods = {
    async setProps(props = {}) {
      const form = await getForm()
      form?.setProps(props)
      if (props.model) {
        form?.setValues(props.model)
      }
    },

    async setValues(data) {
      const form = await getForm()
      form?.setValues(data)
    },

    async setSchema(schemaProps) {
      const form = await getForm()
      form?.setSchema(schemaProps)
    },

    async addSchema(formSchema, index) {
      const form = await getForm()
      form?.addSchema(formSchema, index)
    },

    async delSchema(field) {
      const form = await getForm()
      form?.delSchema(field)
    },

    async getFormData(filterEmptyVal = true) {
      const form = await getForm()
      const model = form?.formModel || {}
      if (filterEmptyVal) {
        return Object.keys(model).reduce((prev, next) => {
          const value = model[next]
          if (!isEmptyVal(value)) {
            if (isObject(value)) {
              if (Object.keys(value).length > 0) {
                prev[next] = value
              }
            } else {
              prev[next] = value
            }
          }
          return prev
        }, {})
      } else {
        return model
      }
    },

    async getComponentExpose(field) {
      const form = await getForm()
      return form?.getComponentExpose(field)
    },

    async getFormItemExpose(field) {
      const form = await getForm()
      return form?.getFormItemExpose(field)
    },

    async getElFormExpose() {
      await getForm()
      return unref(elFormRef)
    },

    async getFormExpose() {
      await getForm()
      return unref(formRef)
    }
  }

  return {
    formRegister: register,
    formMethods: methods
  }
}
